#!/bin/sh

#
#  Copying UltraBench logs
#
#  Copyright (C) 2009 Ultratronik Entwicklungs GmbH
#    - Author: Sören Wellhöfer <soeren.wellhoefer@gmx.net>.
#


# $1 = String
# $2 = Character
# Returns position of char if found; otherwise 0.
#
strchr()
{
    l=`echo $1 | wc -c`
    i=1
    while test $i -lt $l; do
	if test "`echo $1 | cut -b$i`" = "$2"; then
	    return $i
	fi
	i=$((i+1))
    done
    return 0
}

#
# $1 = Character read
#
readchar()
{
    stty raw
    eval $1=`dd if=/dev/tty bs=1 count=1 2>/dev/null`
    stty sane
}

#
# $1 = Question
# $2 = Options (reversed)
# $3 = Default
# $4 = Answer
#
chr_question()
{
    local ans
    printf "$1 ["
    len=`echo $2 | wc -L`
    while test $len -gt 0; do
	chr=`echo $2 | cut -b$len`
	if test "$chr" = "$3"; then
	    printf `echo $chr | tr [:lower:] [:upper:]`
	else
	    printf $chr
	fi
	len=$((len-1))
	if test $len -ne 0; then
	    printf "/"
	fi
    done
    printf "]: "
    readchar ans
    strchr $2 $ans
    if test $? -eq 0; then
      	if test "$ans" = ""; then 
	    eval $4=$3
	else
	    printf "\n"
	    $0 $@
	fi
    else
	eval $4=$ans
    fi
    printf "\n"
}

#
# $1 = Question
# $2 = Answer obtained
#
str_question()
{
    local ans
    tmp="/tmp/logcopy.tmp"
    default=`cat $tmp 2>/dev/null`
    printf "$1 [$default]: "
    read ans
    if test -z $ans; then
	eval $2=$default
    else
	eval $2=$ans
	echo $ans>$tmp 2>/dev/null
    fi
}

logs="/var/log/ubench"

chr_question "Sender/Receiver?" rs s answ
str_question "Name?" name

if test $answ = "s"; then
    mkd="sender"
else
    mkd="receiver"
fi

path="$(dirname `readlink -f $0`)/../logs/$mkd/`date +%s`-${name}"
mkdir -p $path

echo "Copying logs to $path"
cp -R $logs/* $path
